package com.zh.sharding.sale;

import com.alibaba.fastjson.JSON;
import com.zh.mycommon.util.MyDateUtil;
import com.zh.sharding.sale.entity.MyOrders;
import com.zh.sharding.sale.entity.OperateLogRecord;
import com.zh.sharding.sale.service.OrderService;
import com.zh.sharding.sale.support.OperationHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * @author ZH
 * @date 09:13 2023/8/4
 */
@RestController
public class BuyGoodsController {
    @Autowired
    private OrderService orderService;

    @GetMapping("/echo")
    public String echo(@RequestParam String text,@RequestParam(required = false)String date){
        OperateLogRecord logRecord = new OperateLogRecord("hello："+text);

        if (StringUtils.hasLength(date)) {
            String dr = date.trim().substring(0,10); //2022-02-02
            LocalDate localDate = MyDateUtil.parseLocalDate("yyyy-MM-dd", dr);
            logRecord.setCreateTime(LocalDateTime.of(localDate, LocalTime.now()));
        }
        OperationHelper.testLog(logRecord);
        return text;
    }

    /*
    {
    "productId": 1,
    "num": 1,
    "userId": 1001
    }
     */
    @PostMapping("/v1/orders/submit")
    public String addOrder(@RequestBody MyOrders form, @RequestParam Long timestamp) throws Exception {
        OperationHelper.log("下单啦createOrder_lock: form = "+ JSON.toJSONString(form)+" ;\t timestamp = "+timestamp);
        MyOrders orders = new MyOrders(form.getProductId(), form.getNum(), form.getUserId());
        String order = orderService.createOrder_lock(orders);
        return order;
    }

    /*
    {
    "productId": 2,
    "num": 1,
    "userId": 1001
    }
     */
    @PostMapping("/v2/orders/submit")
    public String addOrder2(@RequestBody MyOrders form, @RequestParam Long timestamp) throws Exception {
        OperationHelper.log("下单啦createOrder_new: form = "+ JSON.toJSONString(form)+" ;\t timestamp = "+timestamp);

        MyOrders orders = new MyOrders(form.getProductId(), form.getNum(), form.getUserId());

        String order = orderService.createOrder_new(orders);
        return order;
    }

}
